package com.smart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.smart.entity.*;
import com.smart.mapper.UserMapper;
import com.smart.mapper.UserRoleMapper;
import com.smart.service.UserService;
import com.smart.utils.JwtUtils;
import com.smart.utils.RedisCache;
import com.smart.utils.SnowFlakeUtil;
import com.smart.utils.TransferStringDate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public Toke Login(String username, String password){
//        AuthenticationManager authenticate进行用户认证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username,password);
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
//        如果认证没通过给出对应提示
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("登录失败！");
        }
//        如果认证通过了，使用userid生成jwt，jwt存入Login
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUsers().getUid().toString();
        String jwt = JwtUtils.createJWT(userId);
//        System.out.println("service=====》"+jwt);
//        System.out.println("service=====》"+loginUser);

        // 认证通过 存入 redis
        redisCache.setCacheObject("login:" + userId, loginUser);

        return new Toke(jwt);
    }

    @Override
    public void Logout() {
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Long userId = loginUser.getUsers().getUid();
        // 清空redis
        redisCache.deleteObject("login:" + userId);
    }

    @Override
    public Map<String, Object> UserAll(Integer currentPage, Integer pageSize) {
        Page<Users> page = new Page<>(currentPage,pageSize);//查询的N页，显示N条数据
        IPage<Users> iPage = userMapper.findAllUsers(page);
        Map<String, Object> map = new HashMap<>();
        map.put("total",iPage.getTotal());
        map.put("current",iPage.getCurrent());
        map.put("data", iPage.getRecords());
        return map;
    }

    @Override
    public  Map<String, Object> UserVip(Integer currentPage, Integer pageSize) {
        Page<All_Users> page = new Page<>(currentPage,pageSize);//查询的N页，显示N条数据
        IPage<All_Users> iPage = userMapper.findVipUsers(page);//查询VIP的用户
        Map<String, Object> map = new HashMap<>();
        map.put("total",iPage.getTotal());
        map.put("current",iPage.getCurrent());
        map.put("data", iPage.getRecords());
        return map;
    }

    @Override
    public void UserAdd(Users user) {
        QueryWrapper<Users> query = new QueryWrapper<>();
        query.eq("username",user.getUsername());
        Long i = userMapper.selectCount(query);
        if(i > 0){
            return;
        }

        SnowFlakeUtil snowFlake = new SnowFlakeUtil(2, 3);//调用雪花算法生成18位唯一id
        long randomNumber18 = snowFlake.nextId();//18位唯一id
        user.setUid(randomNumber18);
        user.setRegistertime(new Date());
        user.setStatus(1);
        user.setMoney("0");
        Integer result = userMapper.insert(user); //会帮我们自动生成id

//        给新用户添加身份
        User_Role user_role = new User_Role();
        user_role.setUser_id(randomNumber18);
        user_role.setRole_id(1);
        Integer result1 = userRoleMapper.insert(user_role);
        System.out.println(result); //受影响的行数
        System.out.println(user); //通过日志发现id会自动回填
    }

    @Override
    public Integer UserDelete(Long uid) {
        System.out.println(uid);
        Users users = new Users();
        users.setUid(uid);
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>(users);
        int i = userMapper.delete(queryWrapper);

        User_Role user_role = new User_Role();
        user_role.setUser_id(uid);
        QueryWrapper<User_Role> queryWrappers = new QueryWrapper<>(user_role);
        int j = userRoleMapper.delete(queryWrappers);

        return i;
    }

    @Override
    public List<All_Users> User(String uid) {
        List<All_Users> user = userMapper.findUser(uid);
        return user;
    }

    @Override
    public Integer UserEdit(Map<String, String> user) {
        Users users = new Users();
        users.setRealname(user.get("realname"));
        users.setPassword(user.get("password"));
        users.setTelephone(user.get("telephone"));
        users.setSex(user.get("sex"));
        users.setBirthday(TransferStringDate.transferString1Date(user.get("birthday")));
        users.setLogintime(TransferStringDate.transferString2Date(user.get("logintime")));
        users.setStatus(Integer.valueOf(user.get("status")));
        QueryWrapper<Users> wrapper=new QueryWrapper<>();
        wrapper.eq("UID",user.get("uid"));
        int result= userMapper.update(users, wrapper);

        String temp = user.get("roleremark");
        User_Role userRole = new User_Role();
        if ( temp.equals("1") || temp.equals("基本用户")){
            userRole.setRole_id(1);
        }
        else if ( temp.equals("2") || temp.equals("会员用户")){
            userRole.setRole_id(2);
        }
        else if (temp.equals("系统管理员")){
            userRole.setRole_id(3);
        }
        QueryWrapper<User_Role> querywrapper=new QueryWrapper<>();
        querywrapper.eq("user_id",user.get("uid"));
        int result1 = userRoleMapper.update(userRole, querywrapper);

        return null;
    }

    @Override
    public Users PerInfoAll() {
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        System.out.println("在这里"+loginUser);
        Long userId = loginUser.getUsers().getUid();
        QueryWrapper<Users> usersQueryWrapper = new QueryWrapper<>();
        usersQueryWrapper.eq("uid", userId);
        usersQueryWrapper.select("realname","sex","telephone","birthday");
        Users users = userMapper.selectOne(usersQueryWrapper);

        return users;
    }

    @Override
    public Integer PerInfoEdit(Users user) {
        QueryWrapper<Users> usersQueryWrapper = new QueryWrapper<>();
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Long userId = loginUser.getUsers().getUid();
        usersQueryWrapper.eq("uid", userId);
        Integer update = userMapper.update(user, usersQueryWrapper);
        return update;
    }

    @Override
    public Integer ChangePwdEdit(String password) {
        QueryWrapper<Users> usersQueryWrapper = new QueryWrapper<>();
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Long userId = loginUser.getUsers().getUid();
        usersQueryWrapper.eq("uid", userId);
        Users user = new Users();
        user.setPassword(password);
        Integer update = userMapper.update(user, usersQueryWrapper);
        return update;
    }
}
